<template>
	<view class="baseForm">
		<view class="overhidden">
			<view>
				<!-- <view >
					<scan-bar-h5 ref="scanBarRef" placeholder="请扫描或输入模具编号" @code-scanned="getScanResult" :key="datekey"></scan-bar-h5>
				</view> -->
				
				<view v-if="outWarehouseInfo.taskStatus != 1 && outWarehouseInfo.taskStatus != 2"  style="display: flex; justify-content: center; align-items: center; padding: 10px">
					<scan-bar-h5 ref="scanBarRef" style="flex: 5" placeholder="请扫描或输入模具名称" @code-scanned="getScanResult" :key="datekey"></scan-bar-h5>
				
					<button style="flex: 1" class="danger-btn1" type="primary" @click="jump('/eam/mold/enterWarehouse/components/moldSelect')">选择</button>
				</view>
				<!-- 模具详情 -->
				<!-- <view v-show="!taskInfo?.id && loading === false" class="flex justify-center font-14"
					style="margin: 30px 0 30px 0">暂无模具信息，请录入模具编号</view> -->
				<!-- <ConsumablesDetachInfo v-if="taskInfo.id" :taskInfo="taskInfo"></ConsumablesDetachInfo> -->
				<needMoldInfo v-if="taskinfoList?.length > 0" :taskInfo="taskinfoList" :processesClassification="outWarehouseInfo.processesClassification"></needMoldInfo>
				<!-- 任务详情 -->
				<outWarehouseInfos v-if="outWarehouseInfo.id" :taskInfo="outWarehouseInfo"></outWarehouseInfos>
				<!--  -->
				<u-loading-icon class="flex justify-center mt-20" textSize="18" v-show="loading"></u-loading-icon>

				<!-- <view class="flex justify-center" style="display: flex; width: 100%">
					<view class="flex justify-center">
						<view>
							<u-subsection activeColor="#007aff" mode="subsection" keyName="name" :current="curNow" :list="list" @change="sectionChange"></u-subsection>
						</view>
						<view style="margin-left: -1px">
							<u-subsection activeColor="#007aff" mode="subsection" keyName="name" :current="curNow1" :list="list1" @change="sectionChange1"></u-subsection>
						</view>
					</view>
				</view> -->
				<u-divider style="padding: 0 10px" textColor="black" v-if="planDetailsList?.length > 0" textSize="14" :hairline="false" text="已扫模具"></u-divider>
				<view>
					<u-list ref="tableScroll" class="list" :pagingEnabled="false" :scrollable="false" height="auto">
						<u-list-item v-for="(item, index) in planDetailsList" :key="item.id">
							<view class="card" style="margin-bottom: 0px">
								<view class="flex flex-col justify-between flex-1 h-full record-content-body">
									<view class="flex" style="margin-bottom: 5px">
										<view style="font-size: 15px; flex: 1; font-weight: 700">序号：{{ index + 1 }}</view>
										<view style="font-size: 14px; flex: 1; display: flex; justify-content: flex-end; align-items: center">
											<!-- 是否出库 -->
											<u-icon v-if="item.outboundStatus == '1'" color="#53c21d" name="checkmark-circle-fill" size="18" style="margin-right: 4px"></u-icon>
											<u-icon v-if="item.outboundStatus == '0'" color="#909399" name="info-circle-fill" size="18" style="margin-right: 2px"></u-icon>
											<text style="margin-right: 10px">{{ item.outboundStatus == '1' ? '已出库' : '未出库' }}</text>
											<!-- 是否合格 -->
											<u-icon v-if="item.passStatus == '1'" color="#53c21d" name="checkmark-circle-fill" size="18" style="margin-right: 4px"></u-icon>
											<u-icon v-if="item.passStatus == '0'" color="#e45656" name="close-circle-fill" size="18" style="margin-right: 2px"></u-icon>
											<text>{{ item.passStatus == '1' ? '合格' : '不合格' }}</text>
										</view>
									</view>
									<view class="record-content">
										<view class="record-item">
											<text>模具编号：{{ item.mouldCode }}</text>
											<text></text>
										</view>
										<view class="record-item">
											<text>模具名称：{{ item.mouldName }}</text>
											<text></text>
										</view>
									</view>
								</view>
								<u-line :hairline="false" dashed></u-line>
								<view class="caozuo_line" style="text-align: right; margin-top: 5px">
									<u-tag
										v-if="outWarehouseInfo.taskStatus != 1 && outWarehouseInfo.taskStatus != 2"
										text="点检"
										@click="checkBtn(item)"
										style="margin-right: 10px"
									></u-tag>
									<u-tag v-if="outWarehouseInfo.taskStatus != 1 && outWarehouseInfo.taskStatus != 2" text="删除" @click="deleteBtn(item)" type="error"></u-tag>
									<u-tag v-if="outWarehouseInfo.taskStatus == 1 || outWarehouseInfo.taskStatus == 2" text="查看点检结果" @click="checkBtn(item, 1)"></u-tag>
								</view>
							</view>
						</u-list-item>
					</u-list>
				</view>
				<view v-if="planDetailsList.length == 0 && planLoading === false" class="flex justify-center font-14" style="margin: 30px 0 30px 0">暂无任务详情</view>
				<u-loading-icon class="flex justify-center mt-20" textSize="18" v-show="planLoading"></u-loading-icon>
				<view style="height: 70px" v-if="outWarehouseInfo.taskStatus != 1 && outWarehouseInfo.taskStatus != 2"></view>
				<!-- 提交 -->
				<view class="submit_btn_divTwo" style="margin-bottom: 0px" v-if="outWarehouseInfo.taskStatus != 1 && outWarehouseInfo.taskStatus != 2">
					<button type="default" class="grey_btnTwo" @click="resetBtn">重 置</button>
					<button type="primary" :disabled="postLoading" :loading="postLoading" @click="submit" class="submit_btnTwo">
						{{ isOk() == 0 ? ' 确认维修' : '确认出库' }}
					</button>
				</view>
			</view>
		</view>
	</view>
	<!-- 删除确认 -->
	<u-modal :show="showImport" ref="uModal" content="确认删除该条数据?" confirmText="确认" showCancelButton @cancel="cancelImport" @confirm="confirmImport"></u-modal>
	<!-- 重置所有信息 -->
	<u-modal
		:show="showImportReset"
		ref="uModalReset"
		title="谨慎操作"
		content="请确认是否清除任务中的所有信息?"
		confirmText="确认"
		showCancelButton
		@cancel="cancelImportReset"
		@confirm="confirmImportReset"
	></u-modal>
	<!-- 出库确认 -->
	<u-modal
		:show="showImportOut"
		ref="uModalOut"
		title=""
		:content="`已选择位置: ${position}, 是否立即 ${isOk() == 0 ?'维修':'出库'}?`"
		confirmText="确认"
		showCancelButton
		@cancel="cancelImportOut"
		@confirm="confirmImportOut"
	></u-modal>
 <u-modal
    :show="showImportCheck"
    ref="uModalCheck"
    title=""
    :content="`是否确认维修，不会立即出库，但是会自动创建故障报修单，维修完成后可恢复出库。`"
    confirmText="确认"
    showCancelButton
    @cancel="cancelImportCheck"
    @confirm="confirImportCheck"
    :asyncClose="true"></u-modal>
	<!-- 树形选择器 -->
	<ba-tree-picker
		ref="positionPicker"
		:multiple="false"
		@select-change="positionChange"
		title="位置"
		:selectedData="showPositionValue"
		:localdata="positionList"
		valueKey="id"
		textKey="locationName"
		childrenKey="nodes"
	/>
</template>

<script lang="ts" setup>
import { ref, reactive, toRaw, computed, watch } from 'vue';
import { http } from '@/utils/http';
import { mockData } from './index';
import { onPageScroll, onShow, onLoad } from '@dcloudio/uni-app';
import UploadImage from '@/components/upload-image-ssr.vue';
import ScanBar from '@/components/scan-bar/index.vue';
import ConsumablesDetachInfo from '@/pages/eam/mold/enterWarehouse/components/info.vue';
import needMoldInfo from '@/pages/eam/mold/outWarehouse/components/needMoldInfo.vue';
import outWarehouseInfos from '@/pages/eam/mold/outWarehouse/components/outWarehouseInfo.vue';
import { sizeColorHandle1, sizeColorHandle } from '@/utils/common';
import { toScanCode } from '@/components/hs-scancode/scan.js';
import dayjs from 'dayjs';
import ScanBarH5 from '@/components/ScanBarH5/ScanBarH5.vue';
import { useEamStore } from '@/stores/useEamStore';
// 刚进来 页面置顶
onLoad(() => {
	uni.pageScrollTo({
		scrollTop: 0,
		duration: 0
	});
});
const props = defineProps({
  id: {
    type: String,
    default: () => "",
  },
  
});
onShow(() => {
	props.id && getPlanInfo();
	props.id && getPlanDetails();
	props.id && getTaskinfo();
	getPositionList();
});

// 表单详情
let formData = reactive({
	consumeCode: '',
	consumeName: '',
});

// 初始化页面，获取检查详情
let taskInfo = ref<any>({});
let outWarehouseInfo = ref<any>({});
const loading = ref(false);

// 表单规则定义
const rules = ref({});

// 摄像头参数设置
const capture = ref(['camera', 'album']);

// 获取扫码结果
function getScanResult(result: any) {
	formData.consumeName = result;
	if (result) {
		const findData = taskinfoList.value.find((item) => item.assetName == result);
		if (findData) {
			getDeviceInfo(result);
		} else {
			uni.showToast({
				title: '需要模具数据中未找到该名称！',
				icon: 'none'
			});
			scanBarRef.value && scanBarRef.value.reset();
			datekey.value = new Date();
		}
	}
}

// form信息重置
function resetData() {
	taskInfo.value = {};
	outWarehouseInfo.value = {};
	planDetailsList.value = [];
	curNow1.value = 4;
	curNow.value = 0;

	scanBarRef.value && scanBarRef.value.reset();
	datekey.value = new Date();

	formData.consumeName = '';
	uni.pageScrollTo({
		scrollTop: 0,
		duration: 100
	});
}

// 重置表单信息 & 光标自动blur
const scanBarRef = ref();
const datekey = ref(new Date());
function resetFields() {
	resetData();
}

const showImportOut = ref(false);
const cancelImportOut = () => {
	showImportOut.value = false;
};
const confirmImportOut = async () => {
	console.log('isOk()', isOk());
	// save提交
	postLoading.value = true;
	const result: any = await http({
		method: 'POST',
		url: isOk() == 0 ? `/eam/eammouldtaskinfo/mouldSaveMaintenance` : `/eam/eammouldtaskinfo/mouldSave`,
		data: {
			id: props.id,
			locationId: positionId.value,
			passStatus: isOk()
		}
	}).catch(() => {
		postLoading.value = false;
	});
	if (result?.code == 200) {
		uni.showToast({
			title: `${isOk() == 0 ? '维修' : '出库'}成功！`
		});
		showImportOut.value = false;
		setTimeout(() => {
			postLoading.value = false;
			// resetFields();
			uni.navigateBack();
		}, 500);
	}
};

// 是否都合格

const isOk = () => {
	for (let i = 0; i < planDetailsList.value.length; i++) {
		if (planDetailsList.value[i].passStatus == 0) {
			return 0;
		}
	}
	return 1;
};

// 校验提交
const uForm = ref();
const postLoading = ref(false);
async function submit() {
	
	
	
	if (planDetailsListAll.value.length === 0) {
		uni.showToast({
			title: '暂无录入模具信息，不能执行操作',
			icon: 'none'
		});
		return;
	}
	
	
	if(isOk()==0){
		showImportCheck.value=true
	}else{
		showPositionPicker();
	}
	
	
	// showImportOut.value = true
}

// 获取模具信息（接口请求）
async function getDeviceInfo(consumeName: string) {
	loading.value = true;
	const data: any = await http({
		method: 'GET',
		url: `/eam/mouldAssetInfo/checkName/${consumeName}`,
		data: {}
	}).catch(() => {
		loading.value = false;

		taskInfo.value = {};
		scanBarRef.value && scanBarRef.value.reset();
		datekey.value = new Date();
		// resetFields();
	});
	// getPlanDetails();
	if (data?.data) {
		taskInfo.value = data?.data;
		console.log('taskInfo.value ', taskInfo.value);
		planDetailsSave();

		getPlanInfo();
		scanBarRef.value && scanBarRef.value.reset();
		datekey.value = new Date();
		setTimeout(() => {
			getPlanDetails();
		}, 1000);
	} else {
		taskInfo.value = {};
		scanBarRef.value && scanBarRef.value.reset();
		datekey.value = new Date();
	}
	loading.value = false;
	// 模拟数据返回，调试使用（保留）
	// setTimeout(() => {
	// 	loading.value = false;
	// 	taskInfo.value = JSON.parse(JSON.stringify(mockData));
	// }, 500);
}
// 任务信息
const getPlanInfo = async () => {
	await http({
		method: 'GET',
		url: `/eam/eammouldtaskinfo/get/${props.id}`
	}).then((res) => {
		outWarehouseInfo.value = JSON.parse(JSON.stringify(res.data));
	});
};
// 任务详情
const planDetailsList = ref([]);
const planDetailsListAll = ref([]);
const planLoading = ref(false);
const getPlanDetails = async () => {
	planLoading.value = true;
	await http({
		method: 'POST',
		url: `/eam/eammouldtaskinfo/getDetails`,
		data: {
			id: props.id,
			passStatus: curNow1.value == 4 ? '' : curNow1.value,
			outboundStatus: curNow.value == 0 ? '' : list.value[curNow.value].value
		}
	})
		.then((res) => {
			if (curNow1.value == 4 && curNow.value == 0) {
				planDetailsListAll.value = JSON.parse(JSON.stringify(res.data)) || [];
			}
			planDetailsList.value = JSON.parse(JSON.stringify(res.data)) || [];
		})
		.finally(() => {
			planLoading.value = false;
		});
};
// 扫码保存
const planDetailsSave = async () => {
	// const { mouldName, mouldCode, mouldType, locationId, locationName, outboundStatus, passStatus } = taskInfo.value;
	await http({
		method: 'POST',
		url: `/eam/eammouldtaskinfodetail/save`,
		data: {
			scanTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
			taskId: outWarehouseInfo.value.id,
			mouldName: taskInfo.value.assetName,
			mouldCode: taskInfo.value.assetCode,
			mouldType: taskInfo.value.assetTypeCode,
			locationId: taskInfo.value.locationId,
			locationName: taskInfo.value.locationName,
			outboundStatus: 0,
			passStatus: 1
		}
	}).then((res) => {
		uni.showToast({
			title: '成功！',
			icon: 'none'
		});
	});
};

const list = ref([
	{ name: '全部', value: 2 },
	{ name: '已出库', value: 1 },
	{ name: '未出库', value: 0 }
]);

const curNow = ref(0);

const sectionChange = (index) => {
	if (index == 0) {
		curNow1.value = 4;
	}
	curNow.value = index;
	// curNow.value = list.value[index].value;
	getPlanDetails();
};

const list1 = ref([
	{ name: '不合格', value: 0 },
	{ name: '合格', value: 1 }
]);

const curNow1 = ref(4);

const sectionChange1 = (index) => {
	console.log(index);

	curNow1.value = list1.value[index].value;
	getPlanDetails();
};

const checkBtn = (item, isRead = 0) => {
	uni.navigateTo({
		url: `/pages/eam/mold/outWarehouse/outWarehouseCheck?mouldType=${item.mouldType}&mouldId=${item.id}&isRead=${isRead}`,
		fail: () => {
			uni.showToast({
				title: '敬请期待',
				icon: 'error'
			});
		}
	});
};

// 重置
const resetBtn = async (item) => {
	resetData();
	getPlanInfo();
	getPlanDetails();
	// if (planDetailsListAll.value.length === 0) {
	// 	uni.showToast({
	// 		title: '暂无录入模具信息，无需重置',
	// 		icon:'none'
	// 	})
	// 	return
	// }
	// showImportReset.value = true
};

const showImportReset = ref(false);
const cancelImportReset = () => {
	showImportReset.value = false;
};
const confirmImportReset = async () => {
	await http({
		method: 'POST',
		url: `/eam/eammouldtaskinfodetail/deleteItem/${deleteId.value}`,
		data: {
			id: props.id
		}
	}).then((res) => {
		uni.showToast({
			title: '重置成功！',
			icon: 'none'
		});
		resetData();
		getPlanInfo();
		getPlanDetails();
		showImportReset.value = false;
	});
	showImportReset.value = false;
};

// 删除
const deleteId = ref('');
const deleteBtn = async (item) => {
	showImport.value = true;
	deleteId.value = '';
	deleteId.value = item.id;
};

const showImport = ref(false);
const cancelImport = () => {
	showImport.value = false;
};
const confirmImport = async () => {
	await http({
		method: 'POST',
		url: `/eam/eammouldtaskinfodetail/deleteItem/${deleteId.value}`,
		data: {
			// id: props.id
		}
	}).then((res) => {
		uni.showToast({
			title: '删除成功！',
			icon: 'none'
		});
		getPlanDetails();
		showImport.value = false;
	});
	showImport.value = false;
};

// 位置选择
// 显示选择器
const positionId = ref('');
const position = ref('');
const positionPicker = ref();
function showPositionPicker() {
	positionPicker.value._show();
}
//监听选择（ids为数组）
const showPositionValue = ref([]);
function positionChange(ids, names) {
	positionPicker.value._reTreeList();
	positionId.value = ids[0] ?? '';
	position.value = names ?? '';
	showPositionValue.value = ids[0] ? [ids[0]] : [];
	console.log('positionId', positionId.value);
	showImportOut.value = true;
}

// 清空数据
function clearInfo() {
	positionId.value = '';
	position.value = '';
	if (positionPicker.value?._reTreeList) {
		positionPicker.value._reTreeList();
	}
}
// 获取位置列表
const positionList = ref();
async function getPositionList() {
	const { data } = await http({
		method: 'POST',
		url: `/eam/locationInfo/getTree`,
		data: {}
	});
	positionList.value = data;
}
// eammouldtaskinfo/get/{id}
const taskinfoList = ref([]);
async function getTaskinfo() {
	const { data } = await http({
		method: 'GET',
		url: `/eam/eammouldtaskinfo/get/${props.id}`
	});
	taskinfoList.value = data.assetList || [];
	// taskinfoList.value=[{assetName:'111',assetCode:'222',id:'111'}]
}



const showImportCheck= ref(false);
const cancelImportCheck = () => {
  showImportCheck.value = false;
};
const confirImportCheck = () => {
  showImportCheck.value = false;
  showPositionPicker();
};




function jump(item, id = '') {

		const moldName = encodeURIComponent(scanBarRef.value.assetName||'');
		uni.navigateTo({
			url: id ? `/pages${item}?id=${id}` : `/pages${item}?moldName=${moldName}&type=2`,
			fail: () => {
				uni.showToast({
					title: '敬请期待',
					icon: 'error'
				});
			}
		});
	
}

// 选择模具
// 选择设备信息
const moldData = computed(() => JSON.parse(useEamStore().moldData));
// 监控设备选择id
watch(
	() => moldData,
	async (newVal) => {
		console.log('baocuohuanxing-anzhuang');
		if (newVal.value.id) {
			 console.log(newVal.value);
			
			 setTimeout(() => {
			 	 scanBarRef.value.assetName=newVal.value.assetName
				 getScanResult(newVal.value.assetName)
			 }, 1000);
		}
		setTimeout(() => {
			useEamStore().setMoldDataData({});
		}, 1000);
	},
	{
		deep: true,
		immediate: true
	}
);

</script>

<style lang="scss" scoped>
@import '@/static/css/standard_item.scss';

.upload-scan {
	padding: $uni-page-padding;
	padding-top: 5px;
	padding-bottom: 1px;
	display: flex;
	align-items: center;

	// box-shadow: 0 1px 10px 0px rgb(19 10 236 / 10%);
	.u-icon {
		margin-left: 8px;
	}
}

:deep(.u-search__content) {
	border-color: silver;
}

.submit_btnTwo {
	margin: 0px 20rpx 16rpx 10rpx;
	font-size: 16px;
	height: 45px;
	line-height: 45px;
	box-shadow: 0 1px 10px rgb(3 121 255 / 30%);
}

.grey_btnTwo {
	margin: 0px 10rpx 16rpx 20rpx;
	font-size: 16px;
	height: 45px;
	line-height: 45px;
	border: 1px solid #ccc;
}

.submit_btn_divTwo {
	position: fixed;
	display: flex;
	align-items: center;
	width: 100%;
	bottom: 0;
	z-index: 10;

	uni-button {
		flex: 1;
		border-radius: 10px;
	}
}

.card {
	background-color: #fff;
	border-radius: 8px;
	padding: 10px 12px 5px;
	transition: all 300ms ease;
	box-shadow: 0 2px 6px rgba(3, 121, 255, 0.05);
	border: 1px solid silver;

	.record-title {
		display: flex;
		justify-content: space-between;
		margin: 5px 0 3px 0;
		// color: $primary-color;
		// color: #333 !important;
		word-break: break-all;

		uni-text:nth-child(1) {
			font-weight: bold;
			font-size: 16px;
		}

		uni-text:nth-child(2) {
			// font-weight: bold;
			font-size: 16px;
			min-width: 60px;
			text-align: right;
		}
	}

	.record-item {
		margin: 3px 0 !important;
		// color: #777 !important;
		// color: $primary-color;
		// color: #333 !important;
		display: flex;
		align-items: center;
		font-size: 14px;

		> :first-child {
			min-width: 63px;
		}

		:deep(.u-tag__text--mini) {
			font-size: 13px;
			padding: 1px 3px 0;
		}
	}
}

:deep(.u-subsection__item--first) {
	border-radius: 0px !important;
}

:deep(.u-subsection__item--last) {
	border-radius: 0px !important;
}

:deep(.u-subsection) {
	.u-subsection__item {
		width: calc((100vw - 30px) / 5) !important;
	}
	.u-subsection__item__text {
		font-size: 14px !important;
	}
}

.caozuo_line {
	:deep(.u-tag) {
		padding: 1px 25px;
	}
}
:deep(.searchScan) {
	border: 1px solid silver;
	border-radius: 4px;
}
.danger-btn1 {
	// 更深的红色，增强警示性
	color: #fff;
	border: none;
	border-radius: 0 6px 6px 0; // 更大的圆角
	padding: 0px 16px; // 更舒适的内边距
	margin-left: -3px;
	height: 38px;
	font-size: 15px;
	font-weight: bold; // 加粗文字
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); // 添加阴影
	transition: all 0.3s ease; // 平滑过渡效果
}
</style>
